import { ANIMATION_SPEED } from './JXRBCmdMgr';
import { JXRBRole } from "./JXRBRole";
import { JXRBScript } from "./JXRBScript";
import { JXEState, JXMsg } from './JXULDefine';


/**
 * 环境特效
 */
export class JXRBAmbient extends JXRBRole {
    constructor(object: cc.Node) {
        super(object);
        this._actionList = [];
        this._script = null;
        this.skeleton = object.getComponent(sp.Skeleton);
        if (!this.skeleton) {
            this.skeleton = object.addComponent(sp.Skeleton);
        }
    }

    /**设置spine 数据 */
    public setEffectSkeletonData(data: sp.SkeletonData) {
        if (this.skeleton && this.skeleton.skeletonData) {
            this.skeleton.clearTracks();
            this.skeleton.skeletonData = null;
        }
        this.skeleton.skeletonData = data;
        this.skeleton.timeScale = ANIMATION_SPEED * this.cmd.getSpeed();
        this.skeleton.setEventListener((track: sp.spine.TrackEntry, event: sp.spine.Event) => {
            this.onSkEventListen(this.skeleton, track, event);
        })
    }

    /**更改状态 */
    public changeState(state: JXEState, force = false) {
    }

    /**确认角色对象是否执行完成 */
    public checkRoleIsEnd(): boolean {
        return this._actionList.length == 0 && this.skeleton.skeletonData == null;
    }

    public scrpitExit(script: JXRBScript) {
        if (script != this._script) {
            cc.error('the exit scrpit is not equal mine script! please check the logic!');
            return;
        }
        let skillAns = script._aniConfig.ansInfo as JXAnsSkillInfo;
        if (script.existAcions && script.existAcions.length > 0) {
            for (let i = 0; i < script.existAcions.length; i++) {
                this.addAction(script.existAcions.shift(), true);
            }
            script.existAcions = [];
        }
        this.cmd.evtMgr.post(JXMsg.action.scExit, this);
        this._script = null;
        if (this.effectSkeleton && this.effectSkeleton.skeletonData) {
            this.effectSkeleton.skeletonData = null;
        }
    }

    public scrpitBreak(script: JXRBScript) {
        this._script = null;
    }


    update(dt: number) {
        if (!this.btlActionMgr.hasQueueAction(this) && this._actionList.length > 0) {
            this.addActionToMgr(this, this._actionList.shift());
            return;
        }
        if (this.skeleton && this.skeleton.skeletonData) {
            let track = this.skeleton.getCurrent(0);
            if (track) {
                let aniInfo = this.skeleton.getAnimationInfo(track.animation.name);
                if (aniInfo.duration < track.trackTime) {
                    this.skeleton.clearTracks();
                    this.skeleton.skeletonData = null;
                }
            }
        }
    }
}